package great.easychat.help

import androidx.lifecycle.Lifecycle
import com.pince.frame.FinalActivity
import com.pince.frame.theme.Theme
import com.pince.frame.theme.ThemeHelper
import com.pince.logger.LogUtil
import io.reactivex.annotations.CheckReturnValue
import io.reactivex.subjects.PublishSubject
import java.lang.ref.WeakReference

/**
 * @author athoucai
 * @date 2018/9/7
 */

internal class ActivityProxyImpl(host: FinalActivity) : IActivityProxy {

    private val mHost: WeakReference<FinalActivity> = WeakReference(host)

    private val lifecycleSubject = PublishSubject.create<Lifecycle.Event>()

    private fun assertHostValid() {
        if (mHost == null || mHost!!.get() == null) {
            throw IllegalArgumentException("host lost")
        }
    }

    /**
     * 设置主题背景
     */
    override fun changeTheme() {
        assertHostValid()
        val clazz = mHost.get()!!::class.java
        if (!clazz.isAnnotation()) {
            return
        }
        val theme = clazz.getAnnotation(Theme::class.java)
        theme?.let {
            val themeValue = ThemeHelper.getInstance().getTheme(it.value, mHost.get()?.packageName)
            if (themeValue != 0) {
                mHost.get()?.setTheme(themeValue)
            }
        }
    }


    fun onStart() {
        LogUtil.i("onStart: " + mHost.get()!!::class.java)
    }

    fun onResume() {
        assertHostValid()
        LogUtil.i("onresume: " + mHost.get()!!::class.java)
    }

    fun onPause() {
        assertHostValid()
        LogUtil.i("onPause: " + mHost.get()!!::class.java)
    }

    fun onDestroy() {
        lifecycleSubject.onNext(Lifecycle.Event.ON_DESTROY)
    }

    @CheckReturnValue
    override fun <T> bindUntilEvent(lifeCycleEvent: Lifecycle.Event): IActivityProxy.LifecycleTransformer<T> {
        val compareLifecycleObservable = lifecycleSubject.filter { event -> lifeCycleEvent == event }
        return IActivityProxy.LifecycleTransformer(compareLifecycleObservable)
    }
}
